package cn.net.dpi.util;

import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;

import java.nio.charset.StandardCharsets;

/**
 * Copyright(c) 2022 DaYou Positioning Intelligence Co.,Ltd
 * All rights reserved.
 *
 * @Description
 * @Date 2022/11/2 10:52
 * @Author DPI199
 * @Version v0.1
 */
public class SignUtils {

    private final static String COM_STR = "0123456789abcdef";

    /**
     * 签名方法
     * 参数：content：要发送的JSON结构字符串
     * 返回值：签名信息字符串
     */
    public static String sign(String content) throws java.io.UnsupportedEncodingException {
        String toSign = content + "&" + System.currentTimeMillis();
        return md5(toSign.getBytes(StandardCharsets.UTF_8));
    }

    private static String md5(byte[] toSignBytes) {
        try {
            Digester md = new Digester(DigestAlgorithm.MD5);
            byte[] bytes = md.digest(toSignBytes);
            return toHex(bytes);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String toHex(byte[] bytes) {
        final char[] HEX_DIGITS = COM_STR.toCharArray();
        StringBuilder ret = new StringBuilder(bytes.length * 2);
        for (byte aByte : bytes) {
            ret.append(HEX_DIGITS[(aByte >> 4) & 0x0f]);
            ret.append(HEX_DIGITS[aByte & 0x0f]);
        }
        return ret.toString();
    }
}
